package com.company.management.service;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.framework.pojo.PageResult;
import com.company.management.constant.Constants;
import com.company.management.domain.req.PerformanceResultPageReq;
import com.company.management.domain.req.PerformanceResultsReq;
import com.company.management.domain.reward.ScoreLevel;
import com.company.management.domain.reward.ScoreLog;
import com.company.management.domain.reward.TalentUser;
import com.company.management.domain.rsp.PerformanceEvalResultsResp;
import com.company.management.domain.rsp.PerformanceResultsResp;
import com.company.management.mapper.PerformanceResultsMapper;
import com.company.management.modal.entity.PerformanceEvaluations;
import com.company.management.modal.entity.PerformanceResults;
import com.company.management.service.reward.ScoreLevelService;
import com.company.management.service.reward.ScoreLogService;
import com.company.management.service.reward.TalentUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author robet.li
 * @since 2025-03-02
 */
@Slf4j
@Service
public class PerformanceResultsService extends ServiceImpl<PerformanceResultsMapper, PerformanceResults> {
    @Autowired
    private PerformanceEvaluationsService performanceEvaluationsService;
    @Autowired
    private TalentUserService talentUserService;
    @Autowired
    private ScoreLogService scoreLogService;
    @Autowired
    private ScoreLevelService scoreLevelService;
    @Transactional(rollbackFor = Exception.class)
    public Integer saveResult(PerformanceResultsReq req){
        boolean bSave = false;
        PerformanceResults performanceResults = new PerformanceResults();
        BeanUtils.copyProperties(req,performanceResults);
        performanceResults.setEvaluationId(req.getId());
        performanceResults.setResultId(null);
        performanceResults.setCreateId(req.getUserId());
        performanceResults.setCreateDateTime(new Date());
        performanceResults.setUserId(Integer.parseInt(req.getPersonIds()));
        bSave = this.save(performanceResults);

        if(bSave){
            PerformanceEvaluations bean = new PerformanceEvaluations();
            bean.setEvaluationId(req.getId());
            bean.setFinish(1);
            performanceEvaluationsService.updateById(bean);
            //查询用户信息
            TalentUser talentUsers = talentUserService.getById(performanceResults.getUserId());
            ScoreLog scoreLog = buildScoreLog(talentUsers, performanceResults);
            //新增绩效记录表数据
            scoreLogService.save(scoreLog);
            //更新用户表分数
            talentUserService.saveOrUpdate(talentUsers);
            return 1;
        }else{
            return 0;
        }
    }
    public PageResult<PerformanceEvalResultsResp> getPerformanceResults(PerformanceResultPageReq req){
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<PerformanceEvalResultsResp> list = this.baseMapper.getPerformanceEvalResults(req);
        list.forEach(item->{
            try {
                item.setContent(new String(item.getEvaluationContent(), Constants.GBK));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        });
        PageInfo<PerformanceEvalResultsResp> page = new PageInfo<>(list);
        return new PageResult<>(list, page.getTotal());
    }
    public PerformanceResultsResp detail(String id){
        PerformanceResultsResp resp = new PerformanceResultsResp();
        PerformanceResults bean = this.getById(id);
        if(bean!=null){
            BeanUtils.copyProperties(bean,resp);
            resp.setResCreateTime(bean.getCreateDateTime());
            resp.setFisSuccess(bean.getFisSuccess()!=null?bean.getFisSuccess():0);
            return resp;
        }else{
            return null;
        }
    }
    private ScoreLog buildScoreLog(TalentUser talentUser, PerformanceResults performanceResults){
        //考核是否通过，0不通过，1通过
        Integer fisSuccess = performanceResults.getFisSuccess();
        //0 已完成绩效考核; 1未完成绩效考核
        Integer flag =0;
        if(fisSuccess==0){
            flag =1;
        }
        ScoreLog scoreLog = new ScoreLog();
        //机制表扣分/加分
        Integer rewardScore = 0;
        //机制表ID
        Integer sid = 0;
        String updateScore = "";
        String fName = Constants.PERFORMANCE_MODULE;
        List<ScoreLevel> scoreLevels = scoreLevelService.list(Wrappers.<ScoreLevel>lambdaQuery()
                .eq(ScoreLevel::getFlag,flag).eq(ScoreLevel::getModule,Constants.PERFORMANCE_MODULE_IDX));
        if(!CollectionUtils.isEmpty(scoreLevels)){
            rewardScore = scoreLevels.get(0).getScore();
            sid = scoreLevels.get(0).getSid();
            if (fisSuccess==0){
                //不通过 扣分
                updateScore = String.format(Constants.SUBTRACT,rewardScore);
                rewardScore = -rewardScore;
                fName = Constants.PERFORMANCE_MODULE+Constants.PERFORMANCE_ERROR;
            }else {
                updateScore = String.format(Constants.ADD,rewardScore);
                fName = Constants.PERFORMANCE_MODULE+Constants.PERFORMANCE_SUC;
            }
        }
        scoreLog.setCreateDateTime(new Date());
        scoreLog.setUserId(talentUser.getUserId());
        scoreLog.setFid(Long.valueOf(performanceResults.getResultId()));
        scoreLog.setFName(fName);
        Integer score = talentUser.getScore().intValue();
        scoreLog.setBeforeScore(score);
        scoreLog.setSid(sid);
        //例如：+1,+5,-5,-20
        //具体加减根据机制表的标识字段+每次扣分/加分多少分
        scoreLog.setUpdateScore(updateScore);
        Integer afterScore = score + rewardScore;
        scoreLog.setAfterScore(afterScore);
        talentUser.setScore(new BigDecimal(afterScore));
        return scoreLog;
    }
}
